package com.swt.controller.S_controller;

import com.swt.domain.Aboutcourse;
import com.swt.domain.User;
import com.swt.service.S_service.AboutCourseService;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class AboutCourseController {
    /*注入dao*/
    @Resource(name = "S_aboutCourseService")
    private AboutCourseService aboutCourseService;
    /*预约课程的信息*/
    @RequestMapping("/S_aboutcourse")
    public String aboutCourse(Aboutcourse aboutcourse, HttpServletRequest request){
        /*获取session中的用户*/
        User user = (User)request.getSession().getAttribute("USER_SESSION_KEY");
        user.setUserPhone("11111111111");
        aboutcourse.setAboutcourseUserphone(user.getUserPhone());
        aboutcourse.setAboutcourseUserid(user.getUserId());
        aboutcourse.setAboutcourseUsername(user.getUserName());
        aboutcourse.setAboutcourseStatus("待签到");
        /*在保存课程之前要先判断该用户这个课程是否已经选过了 通过用户的id和课程的id以及选课的时间*/
        //获取课程id
        int courseid=aboutcourse.getAboutcourseCourseid();
        String time=aboutcourse.getAboutcourseTime();
        String date=aboutcourse.getAboutcourseDate();
        //设置离线查询
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Aboutcourse.class);
        detachedCriteria.add(Restrictions.eq("aboutcourseUserid",user.getUserId()));
        detachedCriteria.add(Restrictions.eq("aboutcourseCourseid",courseid));
        detachedCriteria.add(Restrictions.eq("aboutcourseDate",date));
        detachedCriteria.add(Restrictions.eq("aboutcourseTime",time));
        //查询数据库
        List<Aboutcourse> list = aboutCourseService.select(detachedCriteria);
        if(list.size()>0){
            System.out.println("============");
            System.out.println(list);
            return "redirect:user/404.html";
        }else{
            /*保存到数据库*/
            //只有当该课程没有预约过
            aboutCourseService.save(aboutcourse);
            /*保存的同时也要获取课程的信息 将该课程的可约人数-1*/
            aboutCourseService.updatenum(aboutcourse.getAboutcourseCourseid());
            return "redirect:user/info.html";
        }
    }
}
